import { sql, normalizePaginationParams } from "#/utils";
import type { PageInfo, Task } from "#/types";

export default {
  queryList(pageInfo: PageInfo): Promise<Task[]> {
    const { page, pageSize, searchContent } =
      normalizePaginationParams(pageInfo);
    if (searchContent) {
      return sql` 
  SELECT * FROM  t_tasks 
  WHERE name LIKE CONCAT('%', ${searchContent}, '%')
    ORDER BY created_at  
  DESC LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}`;
    }
    return sql` 
  SELECT * FROM  t_tasks 
    ORDER BY created_at  
  DESC LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize} `;
  },
  queryAll(): Promise<Task[]> {
    return sql` 
  SELECT * FROM  t_tasks 
  WHERE status = 1
    ORDER BY created_at  `;
  },
  queryById(id): Promise<Task[]> {
    return sql` 
  SELECT * FROM  t_tasks WHERE id = ${id}`;
  },
  queryTotal(): Promise<{ total: number }[]> {
    return sql`SELECT COUNT(*) AS total FROM t_tasks`;
  },
  insert(data) {
    return sql`
 INSERT INTO t_tasks 
  (id, name, description , job_class,cron_expression,params,status,push_status,push_content,created_at,updated_at)  
    VALUES  
  ( ${data.id},${data.name},${data.description},${data.job_class},${data.cron_expression},${data.params},${data.status},${data.push_status},${data.push_content},${data.created_at},${data.updated_at})`;
  },
  deleteById(id: string) {
    return sql` DELETE FROM t_tasks  WHERE id = ${id}`;
  },
  update(data: Task) {
    return sql`
    UPDATE t_tasks
      SET name=${data.name},description=${data.description},cron_expression=${data.cron_expression},push_status=${data.push_status}, push_content = ${data.push_content},updated_at = ${data.updated_at}
    WHERE id = ${data.id}`;
  },
  updateStatus(data: Task) {
    return sql`
    UPDATE t_tasks
      SET status= ${data.status}
    WHERE id = ${data.id}`;
  },
  queryCount(): Promise<
    { total_tasks: number; active_tasks: number; inactive_tasks: number }[]
  > {
    return sql` 
  SELECT 
    COUNT(*) AS total_tasks,
    COUNT(CASE WHEN status = 1 THEN 1 END) AS active_tasks,
    COUNT(CASE WHEN status = 0 THEN 1 END) AS inactive_tasks
FROM t_tasks;`;
  },
};
